  <template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert
        title="注意！只允许为第三级分类标签创造"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="parentCateChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showParamsDialog"
            >添加参数</el-button
          >
          <!-- 动态参数数据表格 -->
          <el-table :data="manyTabData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  class="rowTag"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>

                <!-- 文本输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                >
                  修改
                </el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showParamsDialog"
            >添加属性</el-button
          >
          <!-- 静态属性数据表格 -->
          <el-table :data="onlyTabData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  class="rowTag"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>

                <!-- 文本输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                >
                  修改
                </el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="this.activeName === 'many' ? '添加动态参数' : '添加静态属性'"
      :visible.sync="paramsDialogVisible"
      width="50%"
      @close="paramsDialogClosed"
    >
      <!-- 输入框 -->
      <el-form
        :model="paramsRuleForm"
        :rules="paramsRules"
        ref="paramsRuleForm"
        label-width="100px"
      >
        <el-form-item
          :label="this.activeName === 'many' ? '动态参数：' : '静态属性：'"
          prop="attr_name"
        >
          <el-input v-model="paramsRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮区域 -->
      <span slot="footer">
        <el-button @click="paramsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="this.activeName === 'many' ? '修改动态参数' : '修改静态属性'"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogVisible = false"
    >
      <!-- 输入框 -->
      <el-form
        :model="editRuleForm"
        :rules="editRules"
        ref="editRuleForm"
        label-width="100px"
      >
        <el-form-item
          :label="this.activeName === 'many' ? '动态参数：' : '静态属性：'"
          prop="attr_name"
        >
          <el-input v-model="editRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮区域 -->
      <span slot="footer">
        <el-button @click="editDialogVisible = false"> 取 消 </el-button>
        <el-button type="primary" @click="editDialog"> 确 定 </el-button>
      </span>
    </el-dialog>

    <!-- 删除参数对话框 -->
    <el-dialog
      title="确认删除?"
      :visible.sync="removeDialogVisible"
      width="50%"
    >
      <span slot="footer">
        <el-button @click="removeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="removeRowData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { Message } from "element-ui"
export default {
  data () {
    return {
      // 所有商品分类的数据
      cateList: [],
      // 级联选择器选中的Keys
      selectedKeys: [],
      // 级联选择器的属性
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 被激活的页签名称
      activeName: 'many',
      // 动态参数的数据
      manyTabData: [],
      // 静态属性的数据
      onlyTabData: [],
      // 控制添加参数对话框的显示与隐藏
      paramsDialogVisible: false,
      // 添加参数对话框的表单数据
      paramsRuleForm: {
        attr_name: ''
      },
      // 添加参数对话框的表单数据的验证规则
      paramsRules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' }
        ]
      },
      // 控制修改参数对话框的显示与隐藏
      editDialogVisible: false,
      // 修改参数对话框的表单数据
      editRuleForm: {
        attr_name: ''
      },
      // 修改参数对话框的表单数据的验证规则
      editRules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' }
        ]
      },
      // 当前操作行的商品数据
      rowData: {},
      // 控制删除参数对话框的显示与隐藏
      removeDialogVisible: false,
      // 文本框输入内容
      // inputValue: '',
      // 切换文本框和添加按钮
      // inputVisible: false
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获得所有商品分类
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('请求商品分类信息失败')
      }
      this.cateList = res.data
      // console.log(this.cateList)

    },
    // 选择项发生变化触发这个函数
    parentCateChange () {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTabData = []
        this.onlyTabData = []
        return
      }
      this.getParamsData()
      // console.log(this.selectedKeys)
    },
    // tab页签点击函数
    handleTabClick () {
      this.getParamsData()
    },
    // 获取分类参数列表
    async getParamsData () {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类参数列表失败')
      }
      // console.log(res.data)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      });

      if (this.activeName === 'many') {
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },
    // 点击按钮显示对话框事件
    showParamsDialog () {
      this.paramsDialogVisible = true
    },
    // 添加对话框的关闭事件
    paramsDialogClosed () {
      this.$refs.paramsRuleForm.resetFields()
    },
    // 点击添加对话框的确认按钮
    addParams () {
      this.$refs.paramsRuleForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.paramsRuleForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        // console.log(res.data)
        this.getParamsData()
        this.paramsDialogVisible = false
      })
    },
    // 单击修改按钮弹出修改对话框事件
    async showEditDialog (rowData) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${rowData.attr_id}`, {
        props: {
          attr_sel: this.activeName,
          attr_vals: this.activeName === 'many' ? rowData.attr_vals : ''
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.$message.success('获取数据成功')
      this.editRuleForm.attr_name = res.data.attr_name
      this.rowData = rowData
      this.editDialogVisible = true
    },
    // 修改对话框确认修改事件
    async editDialog () {
      this.$refs.editRuleForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.rowData.attr_id}`, {
          attr_name: this.editRuleForm.attr_name,
          attr_sel: this.activeName,
          attr_vals: this.activeName === 'many' ? this.rowData.attr_vals : ''
        })
        if (res.meta.status !== 200) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        // console.log(res.data)
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    // 点击删除按钮事件
    removeParams (rowData) {
      this.rowData = rowData
      this.removeDialogVisible = true
    },
    // 点击删除对话框确认事件
    async removeRowData () {
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${this.rowData.attr_id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getParamsData()
      this.removeDialogVisible = false
    },
    // 显示文本输入框
    showInput (row) {
      row.inputVisible = true
      // $nextTick 方法的作用，就是当页面上元素被重新渲染之后，才会指定回调函数之中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      })
    },
    // 点击增加标签切换到输入框状态
    handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      this.saveAttrValues(row)
      // console.log(row)
      row.inputVisible = false
    },
    // 修改或删除attr_vals中参数
    async saveAttrValues (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('添加参数失败')
      }
      this.$message.success('添加参数成功')
    },
    // 关闭或确认输入框
    handleClose (index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrValues(row)
      // const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
      // if (res.meta.status !== 200) {
      //   return this.$message.error('添加参数失败')
      // }
      // row.attr_vals.splice(index, 1)
      // this.$message.success('添加参数成功')
    }
  },
  // 计算属性
  computed: {
    // 如果按钮需要被禁用，则返回 true ，否则返回 false
    isBtnDisabled () {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中的三级分类Id
    cateId () {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.rowTag {
  margin-right: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>